/**
 * FtpUtil.java
 * jp.co.greenblue.framework.util
 *
 * Function： edtftpj-2.0.0 工具简单封装测试 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2010/12/15 		jonsion
 *
 * Copyright (c) 2010, GreenBlue .  All Rights Reserved.
 */

package com.jonsion.framework.util;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FileTransferClient;
import com.enterprisedt.net.ftp.WriteMode;
import com.jonsion.framework.domain.UploadListener;

/**
 * ClassName:FtpUtil Function: TODO edtftpj-2.0.0 工具简单封装测试 Reason: TODO ADD
 * REASON
 * 
 * @author jonsion
 * @version
 * @since Ver 1.1
 * @Date 2010/12/15 11:43:16
 * 
 * @see
 */
public class FtpUtil {
	private static Log log = LogFactory.getLog(FtpUtil.class);
	private FileTransferClient client = null;
	/**
	 * FTP服务器地址
	 */
	private String remoteHost;
	/**
	 * FTP服务器端口
	 */
	private int remotePort;
	/**
	 * FTP 用户名
	 */
	private String userName;
	/**
	 * FTP 密码
	 */
	private String password;
	/**
	 * FTP 连接超时
	 */
	private int timeout;

	private int transferBufferSize;

	private int transferNotifyInterval;
	/**
	 * 控制编码
	 */
	private String controlEncoding;

	
	public FtpUtil(String remoteHost, int remotePort, String userName,
			String password) {
		this(remoteHost, remotePort, userName, password, 1200, 1000, 5000,
				"UTF-8");
		this.connectServer();
	}

	public FtpUtil(String remoteHost, String userName, String password) {
		this(remoteHost, 21, userName, password, 1200, 1000, 5000, "UTF-8");
		this.connectServer();
	}

	public FtpUtil(String remoteHost, int remotePort, String userName,
			String password, String controlEncoding) {
		this(remoteHost, remotePort, userName, password, 1200, 1000, 5000,controlEncoding);
		this.connectServer();
	}

	/**
	 * 连接ftp服务器
	 * 
	 * @return 连接成功标识
	 */
	public boolean connectServer() {
		boolean flag = false;
		client = new FileTransferClient();
		try {
			client.setRemoteHost(remoteHost);
			client.setRemotePort(remotePort);
			client.setUserName(userName);
			client.setPassword(password);
			client.setTimeout(timeout);

			client.setEventListener(new UploadListener(client));
			client.getAdvancedFTPSettings().setTransferBufferSize(1000);
			client.getAdvancedFTPSettings().setTransferNotifyInterval(5000);
			client.getAdvancedFTPSettings().setControlEncoding(controlEncoding);
			client.connect();
			flag = true;

		} catch (FTPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 关闭FTP客户端连接
	 * 
	 * @return 关闭成功标识
	 */
	public boolean disconnect() {
		boolean flag = false;
		try {
			client.disconnect();
			flag = true;
		} catch (FTPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 *            文件
	 * @param ul
	 *            监听器
	 */
	public void ftpUploadFile(File file, UploadListener ul) {
		String fileName = file.getName();
		String filePath = file.getPath();
		try {
			client.uploadFile(filePath, fileName, WriteMode.RESUME);
			int len = (int) client.getSize(fileName);
			log.info("上传文件" + filePath + "完成，大小为" + len + "字节！");
		} catch (FTPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传文件（夹）
	 * 
	 * @param file
	 *            上传文件
	 * @param ul
	 *            上传监听器
	 */
	public void ftpUploadFolder(File file, UploadListener ul) {
		if (file.isFile()) {
			ftpUploadFile(file, ul);
		}
		try {
			if (file.isDirectory()) {
				FTPFile[] ftpFiles = client.directoryList();
				boolean isExist = false;
				// 遍历FTP当前目录的文件文件名，如果存在则停止查找，如果不存在则设计标记为不存在
				for (FTPFile ftpFile : ftpFiles) {
					if (ftpFile.getName().equals(file.getName())) {
						isExist = true;
						break;
					}
				}
				// 如果要上传的目录不存在，则创建上传目录
				if (!isExist) {
					client.createDirectory(file.getName());
				}
				// 设置当前目录
				client.changeDirectory(file.getName());

				// 上传文件的列表
				File[] upFiles = file.listFiles();
				for (File upFile : upFiles) {
					if (upFile.isFile()) {
						ftpUploadFile(upFile, ul);
					} else if (upFile.isDirectory()) {
						ftpUploadFolder(upFile, ul);
					}
				}
				client.changeToParentDirectory();
			}
		} catch (FTPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param localFileName
	 *            本地文件名
	 * @param remoteFileName
	 *            远程文件名
	 * @throws FTPException
	 * @throws IOException
	 */
	public void ftpDownload(String localFileName, String remoteFileName)
			throws FTPException, IOException {
		client.downloadFile(localFileName, remoteFileName, WriteMode.OVERWRITE);
	}

	public FtpUtil(String remoteHost, int remotePort, String userName,
			String password, int timeout, int transferBufferSize,
			int transferNotifyInterval, String controlEncoding) {
		super();
		this.remoteHost = remoteHost;
		this.remotePort = remotePort;
		this.userName = userName;
		this.password = password;
		this.timeout = timeout;
		this.transferBufferSize = transferBufferSize;
		this.transferNotifyInterval = transferNotifyInterval;
		this.controlEncoding = controlEncoding;
	}

	public String getRemoteHost() {
		return remoteHost;
	}

	public void setRemoteHost(String remoteHost) {
		this.remoteHost = remoteHost;
	}

	public int getRemotePort() {
		return remotePort;
	}

	public void setRemotePort(int remotePort) {
		this.remotePort = remotePort;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public int getTransferBufferSize() {
		return transferBufferSize;
	}

	public void setTransferBufferSize(int transferBufferSize) {
		this.transferBufferSize = transferBufferSize;
	}

	public int getTransferNotifyInterval() {
		return transferNotifyInterval;
	}

	public void setTransferNotifyInterval(int transferNotifyInterval) {
		this.transferNotifyInterval = transferNotifyInterval;
	}

	public String getControlEncoding() {
		return controlEncoding;
	}

	public void setControlEncoding(String controlEncoding) {
		this.controlEncoding = controlEncoding;
	}

	public void setClient(FileTransferClient client) {
		this.client = client;
	}

	public FileTransferClient getClient() {
		return client;
	}

	
	public static void main(String[] args) throws FTPException, IOException {
		FtpUtil ftp = new FtpUtil("172.39.8.9", 21, "test", "test");
		File file = new File("C:\\ecodas");
		File file1 = new File("c:\\jxc.txt");
		UploadListener listener = new UploadListener(ftp.client);
		ftp.ftpUploadFolder(file, listener);
		ftp.ftpUploadFile(file1, listener);

		ftp.ftpDownload("c:\\newjxc.txt", "/jxc.txt");

		ftp.disconnect();
	}
}
